#region License

// Copyright (c) 2006-2008, ClearCanvas Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, 
// are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice, 
//      this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above copyright notice, 
//      this list of conditions and the following disclaimer in the documentation 
//      and/or other materials provided with the distribution.
//    * Neither the name of ClearCanvas Inc. nor the names of its contributors 
//      may be used to endorse or promote products derived from this software without 
//      specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, 
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
// OF SUCH DAMAGE.

#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

using ClearCanvas.Common;
using ClearCanvas.Desktop;
using ClearCanvas.Common.Utilities;
using ClearCanvas.ImageViewer;
using ClearCanvas.ImageViewer.Graphics;
using ClearCanvas.ImageViewer.BaseTools;
using ClearCanvas.ImageViewer.Rendering;
using ClearCanvas.Dicom.DataStore;
using ClearCanvas.Dicom;
using ClearCanvas.ImageViewer.StudyManagement;

namespace WindowsPrintPlugin
{
    /// <summary>
    /// Extension point for views onto <see cref="WindowsPrintComponent"/>.
    /// </summary>
    [ExtensionPoint]
    public sealed class WindowsPrintComponentViewExtensionPoint : ExtensionPoint<IApplicationComponentView>
    {
    }

    /// <summary>
    /// WindowsPrintComponent class.
    /// </summary>
    [AssociateView(typeof(WindowsPrintComponentViewExtensionPoint))]
    public class WindowsPrintComponent : ImageViewerToolComponent
	{
		/// <summary>
		/// Constructor
		/// </summary>
        public WindowsPrintComponent(IDesktopWindow desktopWindow)
			: base(desktopWindow)
		{
		}

		public bool WindowsPrintEnabled
		{
			get 
			{
				if (this.ImageViewer == null)
				{
					return false;
				}
				else
				{
					if (this.ImageViewer.SelectedTile == null)
						return false;
					else
						return true;
				}
			}
		}


		public ImageGraphic SelectedGraphics
		{
			get
			{
				if (this.ImageViewer == null)
					return null;

                if (this.ImageViewer.SelectedImageBox == null)
					return null;

                if (this.ImageViewer.SelectedImageBox.SelectedTile == null)
					return null;

                if (this.ImageViewer.SelectedImageBox.SelectedTile.PresentationImage == null)
                    return null;

                PresentationImage image = (PresentationImage)this.ImageViewer.SelectedImageBox.SelectedTile.PresentationImage;

                //for use in future dicom print ...
                /*
                String Uid = image.Uid;
                IDataStoreReader reader = DataAccessLayer.GetIDataStoreReader();
                ISopInstance instance = reader.GetSopInstance(new ClearCanvas.Dicom.Uid(image.Uid));
                String filename = instance.GetLocationUri().LocalDiskPath;*/

                Bitmap bmp = null;
                Graphics g = null;
                int width = 0;
                int height = 0;
                IRenderingSurface surface = null;

                if (typeof(DicomGrayscalePresentationImage) == image.GetType()) {
                    DicomGrayscalePresentationImage img =
                        (DicomGrayscalePresentationImage)image;

                    width = img.ImageSop.Columns;
                    height = img.ImageSop.Rows;

                    bmp = new Bitmap(width, height);
                    g = Graphics.FromImage(bmp);

                    surface = img.ImageRenderer.GetRenderingSurface(g.GetHdc(), width, height);
                }else if (typeof(DicomColorPresentationImage) == image.GetType()) {
                    DicomColorPresentationImage img =
                        (DicomColorPresentationImage)image;

                    width = img.ImageSop.Columns;
                    height = img.ImageSop.Rows;

                    bmp = new Bitmap(width, height);
                    g = Graphics.FromImage(bmp);

                    surface = img.ImageRenderer.GetRenderingSurface(g.GetHdc(), width, height);
                }else {
                    return null;
                }

                bmp = new Bitmap(width, height);
                g = Graphics.FromImage(bmp);
                
                surface.ContextID = g.GetHdc();
                DrawArgs drawArgs = new DrawArgs(surface, DrawMode.Render);
                image.OnDraw(drawArgs);
                drawArgs = new DrawArgs(surface, DrawMode.Refresh);
                image.OnDraw(drawArgs);

                //Get the ImageCodecInfo for the desired target format
                ImageCodecInfo destCodec = BitmapManipulator.FindCodecForType(BitmapManipulator.MimeTypeFromImageFormat(ImageFormat.Jpeg));

                if (destCodec == null)
                {
                    //No codec available for that format
                    throw new ArgumentException("The requested format " +
                                                BitmapManipulator.MimeTypeFromImageFormat(ImageFormat.Jpeg) +
                                                " does not have an available codec installed",
                                                "destFormat");
                }

                //Create an EncoderParameters collection to contain the
                //parameters that control the dest format's encoder
                EncoderParameters destEncParams = new EncoderParameters(1);

                //Use quality parameter
                EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                destEncParams.Param[0] = qualityParam;
               
                return null;
			}
		}

		#region IApplicationComponent methods

		public override void Start()
		{
			base.Start();
		}

		public override void Stop()
		{
			// TODO prepare the component to exit the live phase
			// This is a good place to do any clean up
			base.Stop();
		}

		#endregion

		/*public void CreateVolume()
		{
			if (this.ImageViewer == null)
				return;

			if (this.ImageViewer.SelectedImageBox == null)
				return;

			IDisplaySet selectedDisplaySet = this.ImageViewer.SelectedImageBox.DisplaySet;
			VolumePresentationImage image = new VolumePresentationImage(selectedDisplaySet);

			AddTissueLayers(image);

			IDisplaySet displaySet = new DisplaySet(String.Format("{0} (3D)", selectedDisplaySet.Name), String.Format("VTK.{0}", Guid.NewGuid().ToString()));
			displaySet.PresentationImages.Add(image);
			this.ImageViewer.LogicalWorkspace.ImageSets[0].DisplaySets.Add(displaySet);

			IImageBox imageBox = this.ImageViewer.SelectedImageBox;
			imageBox.DisplaySet = displaySet;
			imageBox.Draw();
			imageBox[0, 0].Select();

			NotifyAllPropertiesChanged();
		}*/

		protected override void OnActiveImageViewerChanged(ActiveImageViewerChangedEventArgs e)
		{
			if (e.DeactivatedImageViewer != null)
				e.DeactivatedImageViewer.EventBroker.DisplaySetSelected -= OnDisplaySetSelected;
			
			if (e.ActivatedImageViewer != null)
				e.ActivatedImageViewer.EventBroker.DisplaySetSelected += OnDisplaySetSelected;

			NotifyAllPropertiesChanged();
		}

		private void OnDisplaySetSelected(object sender, DisplaySetSelectedEventArgs e)
		{
            NotifyPropertyChanged("WindowsPrintEnabled");

			NotifyAllPropertiesChanged();
		}

		/*private void AddTissueLayers(VolumePresentationImage image)
		{
			GraphicCollection layers = image.TissueLayers;

			TissueSettings tissue = new TissueSettings();
			tissue.SelectPreset("Bone");
			layers.Add(new VolumeGraphic(tissue));

			tissue = new TissueSettings();
			tissue.SelectPreset("Blood");
			layers.Add(new VolumeGraphic(tissue));
		}*/
    }
}
